﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace drawDong
{
    public partial class Form9 : Form
    {
        private bool isModelCopy = false;
        private string fileName;

        private int labelHeight = 24;
        private int maxLineNumber = -1;
        private List<TextBox> redLineList = new List<TextBox>();
        private List<TextBox> labelList = new List<TextBox>();
        private CoverStripModel csm;

        public Form9(string p)
        {
            InitializeComponent();
            for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
            {
                this.dataGridView1.Columns[i].Width = 30;
                this.dataGridView1.Columns[i].Resizable = DataGridViewTriState.False;
            }

            var dgvType = this.dataGridView1.GetType();
            var pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            pi.SetValue(this.dataGridView1, true, null);

            fileName = GlobalVariables.fliterPath + @"\" + p + ".txt";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (csm == null)
            {
                MessageBox.Show("请先生成模型", "提示");
                return;
            }
            isModelCopy = true;
        }

        private void Form9_Load(object sender, EventArgs e)
        {
            InsertDatas();
        }

        private void InsertDatas()
        {
            for (int i = 0; i < 95; i++)
            {
                this.dataGridView1.Rows.Add("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            }

            Console.Write(this.dataGridView1.Rows);

            StreamReader sr1 = new System.IO.StreamReader(fileName);
            while (!sr1.EndOfStream)
            {
                string readLine = sr1.ReadLine();
                bool isLabel = readLine.StartsWith("label");
                bool isRedLine = readLine.StartsWith("redLine");

                if (isLabel)
                {
                   string[] arr = readLine.Replace("label:", "").Split(',');
                    foreach (string s in arr)
                    {
                        int idx = Convert.ToInt16(s);
                        addLabel(idx);
                    }
                }
                else if (isRedLine)
                {
                    string[] arr = readLine.Replace("redLine:", "").Split('-');
                    foreach (string s in arr)
                    {
                        string[] arrp = s.Split(':');
                        if (arrp.Length < 2)
                        {
                            continue;
                        }
                        int sidx = Convert.ToInt16(arrp[0]);
                        int eidx = Convert.ToInt16(arrp[1]);

                        addRedLine(sidx, eidx);
                    }
                }
            }
            sr1.Close();
        }

        private void button6_Click(object sender, EventArgs e)
        {

        }

        private void button7_Click(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (redLineList.Count <= 0)
            {
                MessageBox.Show("请生成盖条和红线端", "提示");
                return;
            }

            DialogResult dr = MessageBox.Show("确认第一个红线段作为模型吗", "提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.Cancel)
            {
                return;
            }
            TextBox tb = this.redLineList[0];
            string tag = tb.Tag.ToString();
            string[] arr = tag.Substring(8).Split(':');
            int sindex = Convert.ToInt16(arr[0]);
            int eindex = Convert.ToInt16(arr[1]);

            if (csm == null)
            {
                csm = new CoverStripModel();
            }
            csm.setRedStartIndex(sindex);
            csm.setRedEndIndex(eindex);
            csm.clearCoverStrip();

            foreach (Control control in labelList)
            {
                string tg = control.Tag.ToString();
                int lindex = Convert.ToInt16(tg.Substring(6));
                if (lindex > eindex)
                {
                    break;
                }
                csm.addCoverStrip(lindex);
            }
            Console.Write(csm);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!isModelCopy)
            {
                MessageBox.Show("请点击复制", "提示");
                return;
            }

            if (labelList.Count <= 0)
            {
                MessageBox.Show("请生成盖条", "提示");
                return;
            }

            if (redLineList.Count <= 0)
            {
                MessageBox.Show("请先生成红线段", "提示");
                return;
            }

            isModelCopy = false;
            int sidx = csm.getRedStartIndex();
            int eidx = csm.getRedEndIndex();
            // 获取最后红线端的位置
            TextBox tb = this.redLineList[0];
            string tag = tb.Tag.ToString();
            string[] arr = tag.Substring(8).Split(':');
            int redsindex = Convert.ToInt16(arr[0]);
            int redeindex = Convert.ToInt16(arr[1]);
            // 获取盖条最大的位置
            string tg = this.labelList[0].Tag.ToString();
            int lindex = Convert.ToInt16(tg.Substring(6));
            int idx = maxLineNumber + 1;

            List<int> lst = csm.getLst();
            int firstIdx = lst[0];
            foreach (int ix in lst)
            {
                addLabel(ix - firstIdx + idx);
            }
            addRedLine(idx, idx + eidx - sidx);
        }

        // 添加盖条
        private void addLabel(int rowIndex)
        {
            TextBox tb = new TextBox();
            tb.Tag = "label;" + rowIndex;
            tb.Location = new Point(0, rowIndex * (labelHeight - 1));
            tb.AutoSize = false;
            tb.Height = labelHeight;
            tb.Width = this.button6.Width;
            tb.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
            tb.BackColor = SystemColors.ControlDark;
            tb.Enabled = false;

            labelList.Add(tb);
            this.splitContainer1.Panel2.Controls.Add(tb);
            tb.BringToFront();

            maxLineNumber = maxLineNumber > rowIndex ? maxLineNumber : rowIndex;
        }

        // 添加红线段
        private void addRedLine(int start, int end)
        {
            TextBox tb = new TextBox();
            tb.Tag = "redline:" + start + ":" + end;
            tb.Location = new Point(0, start * (labelHeight - 1));
            tb.AutoSize = false;
            tb.Height = (end - start + 1) * (labelHeight - 1) + 1;
            tb.Width = 10;
            tb.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            tb.BackColor = Color.Red;
            tb.Enabled = false;

            redLineList.Add(tb);
            this.splitContainer1.Panel2.Controls.Add(tb);
            tb.BringToFront();

            maxLineNumber = maxLineNumber > end ? maxLineNumber : end;
        }

        // 成滤镜
        private void button5_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确认成滤镜吗", "提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.Cancel)
            {
                return;
            }

            DirectoryInfo root = new DirectoryInfo(GlobalVariables.fliterPath);
            FileInfo[] files = root.GetFiles();

            int m = 0;
            foreach (FileInfo fi in files)
            {
                string nm = fi.Name.Replace(".txt", "");
                string tg = nm.Substring(nm.Length - 3, 3);
                int n = Convert.ToInt16(tg);
                m = m > n ? m : n;
            }
            ++m;
            string name = m.ToString();
            while (name.Length < 3)
            {
                name = '0' + name;
            }
            name = "滤镜箱" + name;
            string fileName = GlobalVariables.fliterPath + @"\" + name + ".txt";

            createTxtFile(fileName);

            List<string> labelLst = new List<string>();
            foreach (Control control in labelList)
            {
                string tg = control.Tag.ToString();
                labelLst.Add(tg.Substring(6));
            }
            string labels = "label:" + string.Join(",", labelLst.ToArray());
            saveTxt(fileName, labels);

            List<string> redLineLst = new List<string>();
            foreach (Control control in redLineList)
            {
                string tg = control.Tag.ToString();
                redLineLst.Add(tg.Substring(8));
            }
            string redLines = "redLine:" + string.Join("-", redLineLst.ToArray());
            saveTxt(fileName, redLines);

            this.button1.Visible = false;
            this.button2.Visible = false;
            this.button3.Visible = false;
            this.button4.Visible = false;
            this.button5.Visible = false;
            this.button6.Visible = false;
            this.button7.Visible = false;
            this.dataGridView1.Visible = false;
            this.splitContainer1.Panel1MinSize =0;
            this.splitContainer1.SplitterDistance = 0;
        }

        private void saveTxt(string fileName, string txt)
        {
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamWriter streamWriter = new StreamWriter(fileName, true, Encoding.UTF8);
            StringBuilder strBuilder = new StringBuilder();
            try
            {
                strBuilder.Append(txt);
                String content = strBuilder.ToString();
                streamWriter.WriteLine(content);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                streamWriter.Close();
                fileStream.Close();
            }
        }

        private void createTxtFile(String fileName)
        {
            if (File.Exists(fileName))
            {
                return;
            }

            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
            }
        }
    }
}
